<?php

namespace app\common\model\node;

use app\common\model\BaseModel;
use app\common\model\worker\TaskModel;


class NodeProcessModel extends BaseModel
{
    protected $table = 'node_process';

    /**
     * 四象限数组
     * @return array
     */
    public function getDegree()
    {
        $arr = [
            ['key' => 1, 'name' => '重要且紧急'],
            ['key' => 2, 'name' => '重要不紧急'],
            ['key' => 3, 'name' => '紧急不重要'],
            ['key' => 4, 'name' => '不紧急不重要']
        ];
        return $arr;
    }

    /**
     * 表单类型
     * @return array
     */
    public function formType(){
        $arr = [
            ['key'=>'_text','name'=>'普通文本'],
            ['key'=>'_number','name'=>'数字框'],
            ['key'=>'_textarea','name'=>'多行文本'],
            ['key'=>'_uploadImages','name'=>'图片上传'],
            ['key'=>'_uploadFiles','name'=>'附件上传'],
        ];
        return $arr;
    }

    /**
     * 添加
     * @param $data
     * @throws \Exception
     */
    public function add($data)
    {
        $info = $this->where('process_name',$data['process_name'])->where('node_id',$data['node_id'])->find();
        if(!empty($info)) exception('该节点已存在同名的步骤');
        if(isset($data['process_config'])){
            $data['process_config'] = json_encode($data['process_config'],JSON_UNESCAPED_UNICODE);
        }
        return self::create($data);
    }

    /**
     * 编辑
     * @param $data
     * @throws \Exception
     */
    public function edit($data)
    {
        $info = $this->where('process_name',$data['process_name'])->where('node_id',$data['node_id'])->where('id','<>',$data['id'])->find();
        if(!empty($info)) exception('该节点已存在同名的步骤');
        //todo 更改审核人的时候同步更改未完成任务中的审核人
        $info = $this->where('id',$data['id'])->find();
        $taskModel = new TaskModel();
        $taskList = $taskModel->where('process_status',0)->where('process_id',$data['id'])->select();
        if(!empty($taskList)){
            if(($data['is_audit']==0 && $info['audit_admin_id']>0) || ($data['is_audit']==1 && $data['audit_admin_id'] != $info['audit_admin_id'])){
                $taskModel->where('process_status',0)
                    ->where('process_id',$info['id'])
                    ->update(['is_audit'=>$data['is_audit'],'audit_admin_id'=>$data['audit_admin_id'] ?? 0]);
            }
        }
        if(isset($data['process_config'])){
            $data['process_config'] = json_encode($data['process_config'],JSON_UNESCAPED_UNICODE);
        }
        return self::update($data);
    }

    public function getInfo($map){
        $info = $this->where($map)->find();
        $info['process_config'] = empty($info['process_config'])?[]:json_decode($info['process_config'],true);
        return $info;
    }

}
